<template>
  <el-drawer
      id="instance-log"
      :size="logDrawerSize"
      :visible.sync="logDrawer"
      :withHeader="false"
      title="实时日志"
      @close="onCloseLogDrawer"
      @open="onOpenLogDrawer"
  >
    <h1>实时日志
      <el-button
          class="size-btn"
          plain
          size="mini"
          type="primary"
          @click="sizeBtnClick()"
      >{{ sizeBtnText }}
      </el-button>
    </h1>

    <el-input
        v-model="logKey"
        class="logSearch"
        placeholder="请输入关键字"
    ></el-input>
    <ConsoleLog
        :logLines="logLines"
        :logSearchKey="logKey"
        class="consoleLog"
    />
  </el-drawer>
</template>
<script>
import ConsoleLog from "@/components/ConsoleLog";

export default {
  data() {
    return {
      logKey: null,
      logDrawer: false,
      logLines: [],
      rtLogWs: null,
      logDrawerSize: "50%",
      sizeBtnText: "全屏",
    };
  },
  components: {ConsoleLog},
  methods: {
    onWsOpen() {
      console.log("ws open");
    },
    onWsClose() {
      console.log("ws close");
    },
    onWsError() {
      this.logLines.push("日志异常！！");
    },
    onWsMessage(e) {
      this.logLines.push(e.data);
    },
    openLog(instanceId) {
      console.log(this.logLines);
      if (this.rtLogWs) return;
      let wsApi = process.env.VUE_APP_WS_API;
      if (wsApi.length == 0) {
        wsApi = "ws://";
        if (location.protocol.indexOf("https") == 0) {
          wsApi = "wss://";
        }
        wsApi += location.host;
      }
      this.rtLogWs = new WebSocket(wsApi + "/ws/realTimeLog?instanceId=" + instanceId);
      this.rtLogWs.onopen = this.onWsOpen;
      this.rtLogWs.onmessage = this.onWsMessage;
      this.rtLogWs.onclose = this.onWsClose;
      this.rtLogWs.onerror = this.onWsError;
      this.logDrawer = true;
    },
    onOpenLogDrawer() {
    },
    onCloseLogDrawer() {
      this.logLines = [];
      if (this.rtLogWs != null) {
        this.rtLogWs.close();
        this.rtLogWs = null;
      }
    },
    sizeBtnClick() {
      if (this.logDrawerSize == "50%") {
        this.logDrawerSize = "100%";
        this.sizeBtnText = "正常";
      } else {
        this.logDrawerSize = "50%";
        this.sizeBtnText = "全屏";
      }
    },
  },
};
</script>
<style scoped>
#instance-log /deep/ .el-drawer__body {
  overflow: hidden;
  padding-bottom: 43px;
}

#instance-log h1 {
  padding: 10px;
  text-align: center;
}

#instance-log .size-btn {
  float: right;
}

#instance-log .logSearch {
  position: absolute;
  width: 200px;
  right: 30px;
  top: 80px;
  z-index: 1000;
}
</style>